<?php
/**
 * $Id: captcha_controller.php 849 2011-01-13 11:26:08Z gigapromoters $
 * 
 * This file can not be redistributed to anyone without the permission of Giga Promoters
 * Copyright 2005 - 2008, Giga Promoters
 * 						  608 Aggarwal Cyber Plaza
 *						  Netaji Subhash Place, Delhi - 110034
 *						  www.gigapromoters.com
 * 
 *
 * This is parent of parent class of a controller and should not be edited ever without permission.
 * @version 			$Rev: 849 $
 * @lastModifiedBy		$LastChangedBy: gigapromoters $
 * @lastChanged			$Date: 2011-01-13 16:56:08 +0530 (Thu, 13 Jan 2011) $
 * @copyright 			Giga Promoters (www.gigapromoters.com)
 * 
 */

/**
 * This controller is used to output captcha image for forms.
 *
 */
class CaptchaController extends CmsAppController
{
	var $name = 'Captcha';
	var $uses = array();
	var $font = 'monofont.ttf';
	var $components = array('Session');

	function __construct()
	{
		$this->font = APP.DS.'plugins'.DS.'cms'.DS.'vendors'.DS.$this->font;
		parent::__construct();
	}

	/**
	 * Outputs captcha verification image to the page.
	 *
	 * @param unknown_type $width
	 * @param unknown_type $height
	 */
	function image($width='120',$height='40') 
	{
		checkSessionKey();
		Configure::write('debug',0);
		$this->layout='';
		$code = Utility::generateRandomCode(6);
		$this->Session->write('Form.verificationKey', $code);
		/* font size will be 75% of the image height */
		$font_size = $height * 0.75;
		$image = @imagecreate($width, $height) or die('Cannot initialize new GD image stream');
		/* set the colours */
		$background_color = imagecolorallocate($image, 255, 255, 255);
		$text_color = imagecolorallocate($image, 20, 40, 100);
		$noise_color = imagecolorallocate($image, 100, 120, 180);
		/* generate random dots in background */
		for( $i=0; $i<($width*$height)/3; $i++ ) {
			imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noise_color);
		}
		/* generate random lines in background */
		for( $i=0; $i<($width*$height)/150; $i++ ) {
			imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noise_color);
		}
		/* create textbox and add text */
		$textbox = imagettfbbox($font_size, 0, $this->font, $code) or die('Error in imagettfbbox function');
		$x = ($width - $textbox[4])/2;
		$y = ($height - $textbox[5])/2;
		imagettftext($image, $font_size, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
		/* output captcha image to browser */
		header('Content-Type: image/jpeg');
		header('Cache-Control: no-cache');
		header('Pragma: no-cache');
		imagejpeg($image);
		imagedestroy($image);
		exit;
	}
	
	/**
	 * Function to enable easy testing and captcha bypass
	 *
	 */
	function showCode()
	{
		if(Configure::read('debug')>0)
		{
			echo $_SESSION['verification_code'];
		}
		exit;
	}

}

?>